package se.teamstat.server.service;

import java.util.ArrayList;
import java.util.List;

import se.teamstat.client.dto.PlayerDTO;
import se.teamstat.client.service.player.PlayerService;
import se.teamstat.server.dto.DAO;
import se.teamstat.server.dto.PlayerDAO;
import se.teamstat.server.entity.Player;

import com.google.gwt.user.server.rpc.RemoteServiceServlet;

public class PlayerServiceImpl extends RemoteServiceServlet implements PlayerService  {
    
	private static final long serialVersionUID = -4230799592477844460L;
	private DAO<Player> playerDto;
	
	public PlayerServiceImpl() {
		playerDto = new PlayerDAO();
	}
	
	public String getClassName() {
		return Player.class.getName();
	}

	public PlayerDTO save(PlayerDTO dto) {
		Player player = convertDtoToPlayer(dto);
		player = playerDto.save(player);
		return convertPlayerToDto(player);
	}
	
	public void update(PlayerDTO dto) {
		Player player = convertDtoToPlayer(dto);
		playerDto.update(player);
	}
	
	public List<PlayerDTO> getAll() {
		List<Player> players = playerDto.getAll();
		List<PlayerDTO> dtos = new ArrayList<PlayerDTO>(); 
		for(Player player:players) {
			dtos.add(convertPlayerToDto(player));
		}
		return dtos;
	}
	
	private Player convertDtoToPlayer(PlayerDTO dto) {
		Player player = new Player();
		player.setId(dto.getId());
		player.setFirstName(dto.getFirstName());
		player.setLastName(dto.getLastName());
		player.setEmail(dto.getEmail());
		return player;
	}
	
	private PlayerDTO convertPlayerToDto(Player player) {
		PlayerDTO dto = new PlayerDTO();
		dto.setId(player.getId());
		dto.setFirstName(player.getFirstName());
		dto.setLastName(player.getLastName());
		dto.setEmail(player.getEmail());
		return dto;
	}
}
